#include <iostream>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <string.h>
int main()
{
    // 1。创建管道
    int fds[2] = {0};
    int ret = pipe(fds);
    if (ret < 0)
    {
        std::cerr << "make pipe error" << std::endl;
        exit(1);
    }
    // 创建子进程
    pid_t id = fork();
    if (id < 0)
    {
        std::cerr << "fork error" << std::endl;
        exit(2);
    }
    if (id == 0)
    {
        // 子进程 - 读
        close(fds[1]);
        std::cout <<"子进程: " << getpid() <<"-> 等待父进程写入...." << std::endl;
        char buffer[30];
        read(fds[0],buffer,sizeof(buffer));
        buffer[strlen(buffer)] = 0;
        std::cout << "子进程获取父进程内容成功...." << std::endl;
        printf("父进程wirte=> : %s\n", buffer);
        exit(10);
    }
    // 父进程 - 写
    close(fds[0]);
    char buff[30] = {"i am father"};

    std::cout << "父进程写入...." << std::endl;
    write(fds[1], buff, sizeof(buff));

    int status = 0;

    std::cout << "父进程等待子进程...." << std::endl;
    int wid = waitpid(id,&status,0);
    if (wid > 0)
    {
        std::cout << "wait sucess, child process id: " << id << ", exit code " << ((status>>8)&0xff) << std::endl;
    }
    return 0;
}
